package com.gsm.service.impl;

import com.gsm.service.SmsService;
import com.gsm.utils.SmsUtils;
import com.gsm.utils.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void sendSms(String iphoneNo) {
        //随机数
        Integer code = VerifyCodeUtils.getRandom4();
        //发送短信
        SmsUtils.sendCodeByIphoneNo(iphoneNo, code);
        //保存到redis
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        ops.set("login:verify" + iphoneNo, code, 3, TimeUnit.MINUTES);
    }

    @Override
    public boolean selectIphoneNoAndCode(String iphoneNo, String code) {
        boolean flag = true;
        //查询redis中有没有这个key
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        Integer c = (Integer) ops.get("login:verify" + iphoneNo);
        if (c == null || c.intValue() != Integer.valueOf(code).intValue()) {
            flag = false;
        }
        return flag;
    }
}
